from fastapi import Request
from starlette.types import ASGIApp, Receive, Scope, Send

from utils import random_str


class SetSessionMiddleware:
    def __init__(self, app: ASGIApp) -> None:
        """设置一个随机字符串的session"""
        self.app = app

    # scope 请求信息
    # receive 接收请求体
    # send 发送响应体
    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":  # 非http协议
            await self.app(scope, receive, send)
            return

        req = Request(scope, receive, send)

        if not req.session.get("session"):
            req.session.setdefault("session", random_str())

        await self.app(scope, receive, send)
